import Koa, { Context, Next } from 'koa'
import KoaBody from 'koa-body'
import KoaCors from 'koa2-cors'
import KoaStatic from 'koa-static'
import { join } from 'path'

import { database } from './database'
// 新版本需要挂载到服务上
database.initialize()

// 环境变量文件使用
import env from './config/env'
env('dev')

import('./api/login').then((Factor) => {
  new Factor.default()
})
import('./api/user').then((Factor) => {
  new Factor.default()
})
import('./api/post').then((Factor) => {
  new Factor.default()
})

import { router } from './router'

const app = new Koa()

const catchError = async (ctx: Context, next: Next) => {
  try {
    await next()
  } catch (error) {
    const { status = 400, message = '' } = error
    console.log('捕获到异常', message)
    ctx.status = status
    return (ctx.body = {
      status,
      message
    })
  }
}

app
  .use(KoaCors())
  .use(
    KoaBody({
      multipart: true
    })
  )
  .use(KoaStatic(join(process.cwd(), './public')))
  .use(catchError)
  .use(router.routes())
  .listen(process.env.NODE_KOA_POST, () => {
    console.log('服务启动成功')
    console.log(' ')
    console.log(`http://127.0.0.1:${process.env.NODE_KOA_POST}`)
  })
